<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\common\controller\Backend;
use think\Config;
use think\Db;
use think\exception\HttpResponseException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Response;

/**
 * 预检录入
 *
 * @icon fa fa-circle-o
 */
class DetectionLog extends Backend
{
    protected $noNeedLogin=['edit'];
    protected $noNeedRight = ['edit'];
    /**
     * DetectionLog模型对象
     * @var \app\admin\model\DetectionLog
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\DetectionLog;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("newstatusList", $this->model->newstatusList());
    }


    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        foreach ($list as &$row) {
            $detection_json = json_decode($row['detection_json'],'true');
            $row->sample_name = empty($detection_json) ? '' : $detection_json[0]['sample_name'];
        }

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        $str = $row['update_time'] && !empty($row['pdf_url']) && $row['status']==2 ?  "&show=1" : "";//避免一直查看一直上传文件。审核后一天内查看可重复上传
        $row['url']= cdnurl("/html2pdf/#/html2pdf?id=".$ids.$str,true);
        $row['h5path'] = cdnurl("/html2pdf/#/html2pdf?id=".$ids."&show=1",true);
        $row['str'] = $str;
        if (false === $this->request->isPost()) {
            $row = $row->toArray();
            $row['detection_json'] = json_decode($row['detection_json'],'true');
            foreach ($row['detection_json'] as $key => $value){
                $row['detection_json'][$key]['project_name'] = \app\admin\model\Project::where(['id'=>$value['project']])->value('name');
                $row['detection_json'][$key]['method_name'] = \app\admin\model\Menthod::where(['id'=>$value['method']])->value('name');
                $row['detection_json'][$key]['reagent_name'] = \app\admin\model\Reagent::where(['id'=>$value['name']])->value('name');
            }
            $row['image'] = explode(',',$row['image']);
            $row['yimages'] = explode(',',$row['yimages']);
            $row['simages'] = explode(',',$row['simages']);
            $this->view->assign('row', $row);
            $this->view->assign("newstatusList", $this->model->newstatusList());
            return $this->view->fetch();
        }
        $rowarr = $this->request->post('row/a');
        if(!empty($rowarr)){
            $row->ewm_url = $this->build(cdnurl("/html2pdf/#/info?id=".$ids, true));
            $row->status=$rowarr['status'];
            $row->admin_id = $this->auth->id;
            $row->admin_nickname = Admin::where(['id'=>$this->auth->id])->value('nickname');
            $row->update_time = time();
            $row->allowField(true)->save();
        }
        $this->success('已审核');
    }
    public function build($text)
    {
        $config = get_addon_config('qrcode');
        if (isset($config['limitreferer']) && $config['limitreferer']) {
            $referer = $this->request->server('HTTP_REFERER', '');
            $refererInfo = parse_url($referer);
            $refererHost = $referer && $refererInfo ? $refererInfo['host'] : '';
            $refererHostArr = explode('.', $refererHost);
            $wildcardDomain = '';
            if (count($refererHostArr) > 2) {
                $refererHostArr[0] = '*';
                $wildcardDomain = implode('.', $refererHostArr);
            }
            $allowRefererList = $config['allowrefererlist'] ?? '';
            $domainArr = explode("\n", str_replace("\r", "", $allowRefererList));
            $domainArr = array_filter(array_unique($domainArr));
            $domainArr[] = request()->host(true);

            $inAllowList = false;

            if (in_array('*', $domainArr) || ($refererHost && in_array($refererHost, $domainArr)) || ($wildcardDomain && in_array($wildcardDomain, $domainArr))) {
                $inAllowList = true;
            }

            if (!$inAllowList && (!$referer && $config['allowemptyreferer'])) {
                $inAllowList = true;
            }

            if (!$inAllowList) {
                $response = Response::create('暂无权限', 'html', 403);
                throw new HttpResponseException($response);
            }
        }
        $params = $this->request->get();
        $params['logo'] = 1;
        $params['logosize'] = 50;
        $params = array_intersect_key($params, array_flip(['text', 'size', 'padding', 'errorlevel', 'foreground', 'background', 'logo', 'logosize', 'logopath', 'label', 'labelfontsize', 'labelalignment']));

        $params['text'] = $text;
        $params['label'] = '';

        $qrCode = \addons\qrcode\library\Service::qrcode($params);

        // 写入到文件
            $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
            if (!is_dir($qrcodePath)) {
                @mkdir($qrcodePath);
            }
            $filePath = '';
            if (is_really_writable($qrcodePath)) {
                $name = md5(implode('', $params)) . '.' . $config['format'];
                $filePath = $qrcodePath . $name;
                $qrCode->writeFile($filePath);
                $filePath = cdnurl("/uploads/qrcode/".$name,true);
            }
            return $filePath;

    }

    public function curl_get($id){

        $url = cdnurl("/html2pdf/?id=".$id, true);
        var_dump($url);
            $headers = [];
                $headers = array("Content-type: application/json;charset=UTF-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
            $output = curl_exec($curl);
            if (curl_errno($curl)) {
                echo 'Errno' . curl_error($curl);//捕抓异常
            }
            curl_close($curl);
            return $output;

    }

}
